package com.example.homework07.Room;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.homework07.R;

import java.util.List;

public class roomshow extends Fragment {
    String username;
    int age;
    MyRoomDatabase db;
    public roomshow(){
        super(R.layout.room);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        EditText editTextName = getView().findViewById(R.id.roomname);
        EditText editTextAge = getView().findViewById(R.id.roomage);
//        TextView contentTextView = getView().findViewById(R.id.roomshow);
        Button tjButton = getView().findViewById(R.id.roomtj);
        Button xyButton = getView().findViewById(R.id.roomxy);
        db = MyRoomDatabase.getInstance(getActivity());


        tjButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = editTextName.getText().toString();
                age = Integer.parseInt(editTextAge.getText().toString()) ;
                User user = new User();
                user.username = username;
                user.age = age;
                db.userDao().insert(user);
                showUsers(db.userDao().getAll());
            }
        });

        xyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               showUsers(db.userDao().searchUsersByAge(18));
            }
        });
    }


    private void showUsers(List<User> users) {
        TextView userList = getView().findViewById(R.id.roomshow);
        StringBuilder stringBuilder = new StringBuilder("用户信息列表\n");
        for (User user : users)
            stringBuilder.append("ID: ").append(user.id).append(" | Username: ").append(user.username).append(" | Age: ").append(user.age).append("\n");
        userList.setText(stringBuilder.toString());
    }
}
